package com.gis3c.sys.security.shiro.token;

import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gis3c.sys.service.UserService;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;

public class StatelessAuthcFilter extends AccessControlFilter {
	@Autowired private UserService userService;

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
			throws Exception {
		String clientDigest = null;
		Cookie[] cookies = ((HttpServletRequest)request).getCookies();
		if(cookies != null && cookies.length > 0){
			for(Cookie cookie : cookies){
				if(Constants.PARAM_DIGEST.equals(cookie.getName())){
					clientDigest = cookie.getValue();
					break;
				}
			}
		}
		if((clientDigest == null || "".equals(clientDigest))
				&& request.getParameterMap().containsKey(Constants.PARAM_DIGEST)){
			clientDigest = request.getParameter(Constants.PARAM_DIGEST);
		}

//		String username = request.getParameter(Constants.PARAM_USERNAME);
//		Map<String,String[]> params = new HashMap<>(request.getParameterMap());
//		params.remove(Constants.PARAM_DIGEST);
//		StatelessToken token = new StatelessToken(username,params,clientDigest);

		try{
			if(clientDigest == null || "".equals(clientDigest)){
				onLoginFail(response);
				return false;
			}
			//String username = userService.getUserNameByToken(clientDigest);
			//StatelessToken token = new StatelessToken(username,clientDigest);
			StatelessToken token = new StatelessToken(clientDigest);
			getSubject(request,response).login(token);

			userService.updateTokeTime(clientDigest);
		}catch(Exception e){
			onLoginFail(response);
			return false;
		}
		return true;
	}
	
	private void onLoginFail(ServletResponse response)throws IOException{
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		httpResponse.getWriter().write("Sorry, you do not have access rights!");
	}
}
